import type { RouteRecordRaw } from 'vue-router'
import type { MenuItem } from '@/views/main/menu/MainMenuView.vue'

function loadLocalRoutes() {
  //动态获取的添加路由
  //动态获取所有的路由对象，放到数组中
  const localRoutes: any[] = []

  // type ModuleWithDefault = { default: ModuleWithDefault }
  //读取router/main/所有的ts文件
  const files: Record<string, any> = import.meta.glob('@/router/main/**/*.ts', {
    eager: true,
  })

  //将加载的对象添加到localRoutes中
  for (const key in files) {
    const module = files[key]
    localRoutes.push(module.default)
  }

  return localRoutes
}

export let firstMenu: any = null
export function mapMenusToRoutes(userMenus: MenuItem[]) {
  //加载本地路由
  const localRoutes = loadLocalRoutes()

  const routes: RouteRecordRaw[] = []
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      const route = localRoutes.find((item) => item.path === submenu.path)
      if (route) {
        //给route的顶层菜单添加重定向功能（但是只需要添加一次）
        if (!routes.find((item) => item.path === submenu.path)) {
          routes.push({ path: menu.path, redirect: route })
        }
        routes.push(route)
      }
      if (!firstMenu && route) {
        firstMenu = submenu
        console.log('firstmenu' + firstMenu.path)
      }
    }
  }

  return routes
}
/**
 * 根据路径去匹配需要显示的菜单
 * @param path 要匹配的路径
 * @param useMenus 所有菜单
 */
export function mapPathToMenu(path: string, useMenus: MenuItem[]) {
  for (const menu of useMenus) {
    for (const submenu of menu.children) {
      if (submenu.path === path) {
        return submenu
      }
    }
  }
  return null
}

interface IBreadcrumbs {
  name: string
  path?: string
}

export function mapPathToBreadcrumbs(path: string, userMenus: any[]) {
  // 定义面包屑
  const breadcrumbs: IBreadcrumbs[] = []
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      if (submenu.path === path) {
        //  父级
        breadcrumbs.push({ name: menu.menuName, path: menu.path })
        //  子级
        breadcrumbs.push({ name: submenu.menuName, path: submenu.path })
      }
    }
  }
  return breadcrumbs
}
